package test.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import test.base.HttpResponse;
import test.entity.Interest;
import test.entity.Student;
import test.mapper.InterestMapper;
import test.mapper.StudentMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static test.base.EasyResponse.RF;
import static test.base.EasyResponse.UR;

@Api(tags = "学生相关")
@RestController
@RequestMapping("/styudyent")
public class StudyentController {


    // mybatisPlus对应的学生的实体查询适配器
    @Autowired
    StudentMapper studentMapper;

    // mybatisPlus对应的兴趣的实体查询适配器
    @Autowired
    InterestMapper interestMapper;


    @ApiOperation(value = "根据班级获取学生表")
    @GetMapping("getStudentList")
    public HttpResponse getStudentList(@RequestParam String classRoom) throws Exception {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("classRoom", classRoom);
        List<Student> records = studentMapper.selectList(queryWrapper);
        return RF(records);
    }


    @ApiOperation("修改自己成绩")
    @PutMapping("editScore")
    public HttpResponse editScore(@RequestParam String id, @RequestParam long finalScore) throws Exception {


        if (finalScore > 50) {
            // 限制一下别让你们填的期末分数不能超过50分
            finalScore = 50;
        }

        // 填空1 将null置换成获取自己(1行内完成)
        Student self = studentMapper.selectById(id);

        // 填空2 解除注释，并修改自己的期末分数 (1行内完成)
        self.setFinalScore(finalScore);


        // 填空3 解除注释，计算并登记自己的总分数(总分数 = 平时成绩+期末成绩)
        self.setTotalScore(finalScore+self.getMidScore());



        // 限制一下免得你们把分数搞得爆表了
        if (self.getTotalScore() > 100) {

            self.setTotalScore((long) 100);
        }

        return UR(self, studentMapper.updateById(self));

        // swagger中完成时返回的例子
        /*{
            "msg": "success",
            "code": 200,
            "timestamp": "2019-12-24T23:39:58.581",
            "data": {   q1
                        "id": "12017246005",
                        "name": "杨佳琳",
                        "classRoom": "1",
                        "midScore": 0,
                        "finalScore": 50,
                        "totalScore": 50
                     }
          }*/
    }


    @ApiOperation(value = "根据学号获取该人的兴趣爱好")
    @GetMapping("getInterestByStudentId")
    public HttpResponse getInterestByStudentId(@RequestParam String studentId) throws Exception {

        QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.eq("studentId",studentId);

        List<Interest> interestList = interestMapper.selectList(queryWrapper);
        return RF(interestList);
    }


    @ApiOperation(value = "增添自己的兴趣")
    @PostMapping("addMyInterest")
    public HttpResponse addMyInterest(@RequestParam String studentId, String interest, String myDesc) throws Exception {

        // 填空4 修改此处，完成新增interest(个人兴趣对象)
        // 使swagger中用此接口的对象能被根据getInterestByStudentId接口中
        // 输入对应的studentId(学号)返回自己的兴趣列表
        Interest m_interest = new Interest();
        m_interest.setStudentId(studentId);
        m_interest.setInterest(interest);
        m_interest.setMyDesc(myDesc);
        return UR(m_interest, interestMapper.insert(m_interest));  // (注此处-1需要修改)
//
//       swagger中完成时返回的例子
//        {
//            "msg": "success",
//                "code": 200,
//                "timestamp": "2019-12-25T00:25:43.675",
//                "data": [
//                  {
//                       "id": "1",
//                       "studentId": "1",
//                       "interest": "123",
//                       "myDesc": 456
//                  }
//              ]
//        }

    }



    @ApiOperation(value = "学生表Excel导出")
    @GetMapping("getExcel")
    public void get(HttpServletResponse res, @RequestParam String classRoom) throws IOException {
        String fileName = "result_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ".xlsx";
        // 讲请求结果转换成流
//        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        OutputStream os = res.getOutputStream();

        QueryWrapper queryWrapper = new QueryWrapper();

        // 根据班级名称查询
        queryWrapper.eq("classRoom", classRoom);
        // 根据id排序
        queryWrapper.orderByAsc("id");
        List<Student> records = studentMapper.selectList(queryWrapper);
//        List<Student> records = studentMapper.selectList(null);
        List<Student> addList = new ArrayList<>();

        records.forEach(x -> {
            Student recordExcelBean = new Student();
            recordExcelBean.setId(x.getId());
            recordExcelBean.setName(x.getName());
            recordExcelBean.setClassRoom("17NIIT" + x.getClassRoom() + "班");
            recordExcelBean.setTotalScore(x.getTotalScore());
            recordExcelBean.setMidScore(x.getMidScore());
            recordExcelBean.setFinalScore(x.getFinalScore());
            addList.add(recordExcelBean);
        });
        Workbook workbook = ExcelExportUtil.exportBigExcel(new ExportParams("17NIIT" + classRoom + "班软件实例分析成绩单", "表1"),
                Student.class, addList);
        workbook.write(os);
        os.close();
        addList.clear();
    }

    @ApiOperation("导入学生表")
    @PostMapping("setExcel")
    public HttpResponse post(MultipartFile file, @RequestParam String classRoom) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        List<Student> list = ExcelImportUtil.importExcel(file.getInputStream(), Student.class, params);

        // 计算总共更新了多少条
        AtomicInteger count = new AtomicInteger();
        list.forEach(x -> {
            Student excel = new Student();
            excel.setId(x.getId());
            excel.setName(x.getName());
            excel.setClassRoom(classRoom);
            // 默认分数0
            excel.setTotalScore((long) 0);
            excel.setMidScore((long) 0);
            excel.setFinalScore((long) 0);
            excel.insert();
            count.getAndIncrement();
        });

        return UR(list, count.get());
    }


}